package top.blackr.folivora.common.security.auth.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.captcha.service.ICaptchaService;
import net.dreamlu.mica.core.utils.BeanUtil;
import org.springframework.stereotype.Service;
import top.blackr.folivora.common.core.constants.CommonConstants;
import top.blackr.folivora.common.security.auth.LoginAuthentication;
import top.blackr.folivora.common.security.auth.SecUser;
import top.blackr.folivora.common.security.crud.model.entity.SysUser;
import top.blackr.folivora.common.security.crud.repository.SysUserRepository;

import java.util.Map;


/**
 * 验证码登录
 */
@Slf4j
@AllArgsConstructor
@Service(CommonConstants.LoginType.CODE)
public final class CodeLoginServiceImpl extends DefaultLoginService {

    private final ICaptchaService captchaService;
    private final SysUserRepository sysUserRepository;

    @Override
    public SecUser authentication(LoginAuthentication authentication) {
        Map<String, String[]> parameterMap = authentication.getParameterMap();
        String username = String.valueOf(authentication.getPrincipal());
        String code = String.valueOf(authentication.getCredential());
        String repCode = parameterMap.get("repCode")[0];
        if (StrUtil.isEmptyIfStr(code) || StrUtil.isEmptyIfStr(repCode) || StrUtil.isEmptyIfStr(username)) {
            log.debug("{},必要参数为空！", username);
            throw new RuntimeException(String.format("%s,必要参数为空！", username));
        }
        // 验证code todo 9999通用测试验证码
        boolean validate = StrUtil.equals(code, "9999") || captchaService.validate(repCode, code);
        if (!validate) {
            log.debug("{},验证码错误！{}", username, code);
            throw new RuntimeException(String.format("%s,验证码错误！%s", username, code));
        }
        // 获取用户
        SysUser userInfo = sysUserRepository.getOne(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getUsername, username)
                .last("limit 1"));
        return BeanUtil.copy(userInfo, SecUser.class);
    }
}
